package com.zw.mes.module.shipments.service;


import com.zw.mes.entity.shipments.*;
import com.zw.mes.module.cost.model.Project;
import com.zw.mes.module.prodtaskmanager.entity.ProdTas;
import com.zw.mes.module.prodtaskmanager.service.ProdOrdService;
import com.zw.mes.module.shipments.mapper.InstDeliveryMapper;
import com.zw.mes.module.shipments.mapper.InstDispatchingCreateMapper;
import com.zw.mes.module.shipments.model.DebuggerAll;
import com.zw.mes.module.shipments.repository.*;
import com.zw.mes.module.system.service.LogService;
import com.zw.mes.util.FileUtils;
import com.zw.mes.util.ShiroUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import javax.xml.crypto.Data;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

/**
 * @Description:
 * @Author: China.wsg
 * @Date: 2020/11/10 15:11
 */
@Service
@SuppressWarnings("all")
public class InstDispatchingCreateService {


    @Autowired
    private LogService logService;
    @Autowired
    private InstDispatchingRepository instDispatchingRepository;
    @Autowired
    private InstDispatchingDetailRepository instDispatchingDetailRepository;
    @Autowired
    private InstDispatchingCreateMapper instDispatchingCreateMapper;
    @Value("${user.upload.path}")
    private String uploadPath;
    @Autowired
    private InstDispatchingFileRepository instDispatchingFileRepository;
    @Autowired
    private InstDeliveryMapper instDeliveryMapper;
    @Autowired
    private ProdOrdService prodOrdService;
    @Autowired
    private InstDebuggingDetailRepository instDebuggingDetailRepository;
    @Autowired
    private InstDebuggingFileRepository instDebuggingFileRepository;


    /**
     * 保存安装派工单
     *
     * @param instDispatchingList
     * @param special
     * @param installPrincipal
     * @param installTime
     * @param isDebugging
     * @param installRemark
     * @return
     * @throws ParseException
     */
    @Transactional(rollbackFor = Exception.class)
    public int saveAll(InstDispatchingList instDispatchingList, String[] special, String[] installPrincipal,
                       String[] installTime, Integer[] isDebugging, String[] installRemark) throws ParseException {
        instDispatchingList.setIsDel(0);
        instDispatchingList.setAuthor(ShiroUtils.getUser().getName());
        instDispatchingList.setAuthorTime(new Date());
        instDispatchingList.setUpdateName(ShiroUtils.getUser().getName());
        instDispatchingList.setUpdateTime(new Date());
        instDispatchingList.setSubStatus(1);
        instDispatchingList.setDebuggingStatu("1");
        instDispatchingList.setInstallStatu("1");
//        int k = 0;
//        for (int i = 0; i < isDebugging.length; i++) {
//            if (isDebugging[i] > 0) {
//                k++;
//            }
//        }
//        if (k > 0) {
//            instDispatchingList.setIsDebugging(1);
//        } else {
//            instDispatchingList.setIsDebugging(2);
//        }
        InstDispatchingList instDispatchingList1 = instDispatchingRepository.save(instDispatchingList);
        logService.saveLog("创建安装派工单主单", "项目编号：" + instDispatchingList1.getProCode() + "<br>主键ID：" + instDispatchingList1.getId());
        for (int i = 0; i < special.length; i++) {
            InstDispatchingDetail instDispatchingDetail = new InstDispatchingDetail();
            instDispatchingDetail.setSheetId(instDispatchingList1.getId());
            instDispatchingDetail.setSpecial(special[i]);
            instDispatchingDetail.setInstallPrincipal(installPrincipal[i]);
            instDispatchingDetail.setInstallTime(StrToDate(installTime[i]));
//            instDispatchingDetail.setIsDebugging(isDebugging[i]);
//            if (isDebugging[i] == 1) {
//                instDispatchingDetail.setDebuggingStatus("1");
//            } else {
//                instDispatchingDetail.setDebuggingStatus("0");
//            }
            instDispatchingDetail.setInstallStatus("1");
            if (installRemark.length > 0) {

                instDispatchingDetail.setInstallRemark(installRemark[i]);
            }
            instDispatchingDetail.setIsDel(0);
            InstDispatchingDetail instDispatchingDetail1 = instDispatchingDetailRepository.save(instDispatchingDetail);
            logService.saveLog("创建安装派工单明细单", "id：" + instDispatchingDetail1.getId() + "<br>专业：" + instDispatchingDetail1.getSpecial());
        }
        return 1;
    }

    /**
     * 修改安装派工单
     *
     * @param instDispatchingList
     * @param special
     * @param installPrincipal
     * @param installTime
     * @param isDebugging
     * @param installRemark
     * @return
     * @throws ParseException
     */
    @Transactional(rollbackFor = Exception.class)
    public int editAll(InstDispatchingList instDispatchingList, Integer[] idd, String[] special, String[] installPrincipal,
                       String[] installTime, Integer[] isDebugging, String[] installRemark) throws ParseException {
        InstDispatchingList instDispatchingList1 = instDispatchingRepository.getOne(instDispatchingList.getId());
        instDispatchingList1.setProdNo(instDispatchingList.getProdNo());
        instDispatchingList1.setProdNum(instDispatchingList.getProdNum());
        instDispatchingList1.setProCode(instDispatchingList.getProCode());
        instDispatchingList1.setProName(instDispatchingList.getProName());
        instDispatchingList1.setCustomer(instDispatchingList.getCustomer());
        instDispatchingList1.setInstallPlace(instDispatchingList.getInstallPlace());
        instDispatchingList1.setInstallNum(instDispatchingList.getInstallNum());
        instDispatchingList1.setDesignLeader(instDispatchingList.getDesignLeader());
        instDispatchingList1.setProjectLeader(instDispatchingList.getProjectLeader());
        instDispatchingList1.setFactoryNumber(instDispatchingList.getFactoryNumber());
        instDispatchingList1.setInstallationRequirements(instDispatchingList.getInstallationRequirements());
        instDispatchingList1.setUpdateName(ShiroUtils.getUser().getName());
        instDispatchingList1.setUpdateTime(new Date());
//        int k = 0;
//        for (int i = 0; i < isDebugging.length; i++) {
//            if (isDebugging[i] > 0) {
//                k++;
//            }
//        }
//        if (k > 0) {
//            instDispatchingList1.setIsDebugging(1);
//        } else {
//            instDispatchingList1.setIsDebugging(2);
//        }
        InstDispatchingList instDispatchingList12 = instDispatchingRepository.save(instDispatchingList1);
        logService.saveLog("创建安装派工单主单", "项目编号：" + instDispatchingList1.getProCode() + "<br>主键ID：" + instDispatchingList1.getId());
        for (int i = 0; i < special.length; i++) {
            InstDispatchingDetail instDispatchingDetail = instDispatchingDetailRepository.getOne(idd[i]);
            instDispatchingDetail.setSpecial(special[i]);
            instDispatchingDetail.setInstallPrincipal(installPrincipal[i]);
            instDispatchingDetail.setInstallTime(StrToDate(installTime[i]));
//            instDispatchingDetail.setIsDebugging(isDebugging[i]);
//            if (isDebugging[i] == 1) {
//                instDispatchingDetail.setDebuggingStatus("1");
//            } else {
//                instDispatchingDetail.setDebuggingStatus("0");
//            }
            if (installRemark.length > 0) {

                instDispatchingDetail.setInstallRemark(installRemark[i]);
            }
            InstDispatchingDetail instDispatchingDetail1 = instDispatchingDetailRepository.save(instDispatchingDetail);
            logService.saveLog("修改安装派工单明细单", "id：" + instDispatchingDetail1.getId() + "<br>专业：" + instDispatchingDetail1.getSpecial());
        }
        return 1;
    }

    /**
     *  
     * 字符串转换成日期 
     *
     * @param str 
     * @return date 
     */

    public static Date StrToDate(String str) {
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
        Date date = null;
        try {
            date = format.parse(str);
        } catch (ParseException e) {
            e.printStackTrace();
        }
        return date;
    }

    /**
     * 调试任务反馈列表
     *
     * @param instDispatchingList
     * @return
     */
    public List<InstDispatchingList> findinstDispatchingQuery(InstDispatchingList instDispatchingList) {
        return instDispatchingCreateMapper.findinstDispatchingQuery(instDispatchingList);
    }

    /**
     * 调试反馈明细
     *
     * @param instDispatchingDetail
     * @return
     */
    public List<InstDispatchingDetail> findinstDispatchingDetailQuery(InstDispatchingDetail instDispatchingDetail) {
        return instDispatchingCreateMapper.findinstDispatchingDetailQuery(instDispatchingDetail);
    }

    /**
     * 维护调试进度
     *
     * @param instDispatchingDetail
     * @return
     */
    @Transactional(rollbackFor = Exception.class)
    public Integer saveInstDispatchingDetail(InstDebuggingDetail instDebuggingDetail) {
        InstDebuggingDetail instDebuggingDetail1 = instDebuggingDetailRepository.getOne(instDebuggingDetail.getId());
        instDebuggingDetail1.setStatus(instDebuggingDetail.getDebuggingStatus());
        instDebuggingDetail1.setRemark(instDebuggingDetail.getRemark());
        instDebuggingDetail1.setStaTime(instDebuggingDetail.getStaTime());
        instDebuggingDetail1.setStoTime(instDebuggingDetail.getStoTime());
        instDebuggingDetail1.setUpdateName(ShiroUtils.getUser().getName());
        instDebuggingDetail1.setUpdateTime(new Date());
        InstDebuggingDetail instDebuggingDetail2 = instDebuggingDetailRepository.save(instDebuggingDetail1);
        logService.saveLog("维护调试进度", "id：" + instDebuggingDetail.getId() + "<br>生产令号：" + instDebuggingDetail1.getProCode());
        //反写销售系统调试状态
        int a = instDispatchingCreateMapper.updateProStatus(instDebuggingDetail2);

        return 1;
    }

    /**
     * 查询调试文件
     *
     * @param instDispatchingFile
     * @return
     */
    public List<InstDispatchingFile> findinstDispatchingFileQuery(InstDispatchingFile instDispatchingFile) {
        return instDispatchingCreateMapper.findinstDispatchingFileQuery(instDispatchingFile);
    }

    /**
     * 文件上传调试
     *
     * @param instDispatchingFile
     * @param file
     */
    public void uploadFileExp(InstDebuggingFile instDebuggingFile, MultipartFile file) {
        // 取得项目信息
        String path = uploadPath + instDebuggingFile.getSheetId() + "/" + "debugging/";
        String fileName = FileUtils.upload(file, path);
        String url = "/files/" + instDebuggingFile.getSheetId() + "/" + "debugging/" + fileName;
        instDebuggingFile.setFileName(fileName);
        instDebuggingFile.setIsDel(0);
        instDebuggingFile.setUploadName(ShiroUtils.getUser().getName());
        instDebuggingFile.setUploadTime(new Date());
        instDebuggingFile.setUrl(url);
        instDebuggingFile.setIsGet(2);
        InstDebuggingFile InstDebuggingFile1 = instDebuggingFileRepository.save(instDebuggingFile);
        logService.saveLog("上传附件", "id：" + InstDebuggingFile1.getId() + "<br>" + fileName);
    }
    /**
     * 文件上传安装
     *
     * @param instDispatchingFile
     * @param file
     */
    public void uploadFileExpStall(InstDispatchingFile instDispatchingFile, MultipartFile file) {
        // 取得项目信息
        String path = uploadPath + instDispatchingFile.getSheetId() + "/" + "stall/";
        String fileName = FileUtils.upload(file, path);
        String url = "/files/" + instDispatchingFile.getSheetId() + "/" + "stall/" + fileName;
        instDispatchingFile.setFileName(fileName);
        instDispatchingFile.setIsDel(0);
        instDispatchingFile.setUploadName(ShiroUtils.getUser().getName());
        instDispatchingFile.setUploadTime(new Date());
        instDispatchingFile.setUrl(url);
        InstDispatchingFile instDispatchingFile1 = instDispatchingFileRepository.save(instDispatchingFile);
        logService.saveLog("上传附件", "id：" + instDispatchingFile1.getId() + "<br>" + fileName);
    }
    /**
     * 修改说明文件安装
     *
     * @param instDispatchingFile
     * @return
     */
    public int updExplainById(InstDispatchingFile instDispatchingFile) {
        InstDispatchingFile instDispatchingFile1 = instDispatchingFileRepository.getOne(instDispatchingFile.getId());
        instDispatchingFile1.setRemark(instDispatchingFile.getRemark());
        instDispatchingFileRepository.save(instDispatchingFile1);
        logService.saveLog("修改附件描述", "id：" + instDispatchingFile1.getId() + "<br>" + instDispatchingFile.getRemark());
        return 1;
    }
    /**
     * 修改说明文件调试
     *
     * @param instDispatchingFile
     * @return
     */
    public int updExpDebugging(InstDebuggingFile instDebuggingFile) {
        InstDebuggingFile instDebuggingFile1 = instDebuggingFileRepository.getOne(instDebuggingFile.getId());
        instDebuggingFile1.setFileRemark(instDebuggingFile.getFileRemark());
        instDebuggingFileRepository.save(instDebuggingFile1);
        logService.saveLog("修改附件描述", "id：" + instDebuggingFile1.getId() + "<br>" + instDebuggingFile.getFileRemark());
        return 1;
    }
    /**
     * 删除附件安装
     *
     * @param instDispatchingFile
     * @return
     */
    public int delExp(InstDispatchingFile instDispatchingFile) {
        InstDispatchingFile instDispatchingFile1 = instDispatchingFileRepository.getOne(instDispatchingFile.getId());
        instDispatchingFile1.setIsDel(1);
        instDispatchingFile1.setUploadTime(new Date());
        instDispatchingFile1.setUploadName(ShiroUtils.getUser().getName());
        instDispatchingFileRepository.save(instDispatchingFile1);
        logService.saveLog("删除附件", "id：" + instDispatchingFile1.getId() + "<br>删除人：" + ShiroUtils.getUser().getName());
        return 1;
    }
    /**
     * 删除附件调试
     *
     * @param instDispatchingFile
     * @return
     */
    public int delExpDebugging(InstDebuggingFile instDebuggingFile) {
        InstDebuggingFile instDebuggingFile1 = instDebuggingFileRepository.getOne(instDebuggingFile.getId());
        instDebuggingFile1.setIsDel(1);
        instDebuggingFile1.setUploadTime(new Date());
        instDebuggingFile1.setUploadName(ShiroUtils.getUser().getName());
        instDebuggingFileRepository.save(instDebuggingFile1);
        logService.saveLog("删除附件", "id：" + instDebuggingFile1.getId() + "<br>删除人：" + ShiroUtils.getUser().getName());
        return 1;
    }

    /**
     * 安装派工单提交
     *
     * @param id
     * @return
     */
    public int sumitInstDispatching(Integer id) {
        InstDispatchingList instDispatchingList = instDispatchingRepository.getOne(id);
        instDispatchingList.setSubStatus(2);
        instDispatchingRepository.save(instDispatchingList);
        logService.saveLog("提交安装派工单", "id：" + id + "<br>提交人-时间：" + ShiroUtils.getUser().getName() + "-" + (new Date()));
        return 1;
    }

    /**
     * 安装派工单删除
     *
     * @param id
     * @return
     */
    public int delInstDispatching(Integer id) {
        InstDispatchingList instDispatchingList = instDispatchingRepository.getOne(id);
        instDispatchingList.setIsDel(1);
        instDispatchingRepository.save(instDispatchingList);
        logService.saveLog("删除安装派工单", "id：" + id + "<br>删除人-时间：" + ShiroUtils.getUser().getName() + "-" + (new Date()));
        return 1;
    }

    /**
     * 审核数据
     *
     * @param id
     * @return
     */
    @Transactional(rollbackFor = Exception.class)
    public int examineInstDispatching(Integer id) {
        InstDispatchingList instDispatchingList = instDispatchingRepository.getOne(id);
        instDispatchingList.setSubStatus(3);
        instDispatchingList.setExamineName(ShiroUtils.getUser().getName());
        instDispatchingList.setExamineTime(new Date());
        instDispatchingList.setExamineCode(ShiroUtils.getUser().getAccount());
        instDispatchingRepository.save(instDispatchingList);
        logService.saveLog("审核安装派工单", "id：" + id + "<br>审核人-时间：" + ShiroUtils.getUser().getName() + "-" + (new Date()));
        //更新 prod_pla_ret 表 完成时间
        InstDelivery instDelivery = new InstDelivery();
        instDelivery.setCreateTime(new Date());
        instDelivery.setProdNo(instDispatchingList.getProCode());
        for (int i = 2; i < 5; i++) {
            instDelivery.setDept("r2" + i);
            int a = instDeliveryMapper.updateProdPlaRet(instDelivery);
        }
        return 1;
    }

    /**
     * 驳回
     *
     * @param instDispatchingList
     * @return
     */
    public int reject(InstDispatchingList instDispatchingList) {
        InstDispatchingList instDispatchingList1 = instDispatchingRepository.getOne(instDispatchingList.getId());
        instDispatchingList1.setSubStatus(1);
        instDispatchingList1.setRejectReason(instDispatchingList.getRejectReason());
        instDispatchingRepository.save(instDispatchingList1);
        logService.saveLog("驳回安装派工单", "id：" + instDispatchingList.getId() + "<br>驳回人-时间：" + ShiroUtils.getUser().getName() + "-" + (new Date()));
        return 1;
    }

    /**
     * 安装调试进度
     *
     * @param instDispatchingDetail
     * @return
     */
    @Transactional(rollbackFor = Exception.class)
    public int saveInstDispatchingDetailnstall(InstDispatchingDetail instDispatchingDetail) {
        InstDispatchingDetail instDispatchingDetail1 = instDispatchingDetailRepository.getOne(instDispatchingDetail.getId());
        instDispatchingDetail1.setInstallEndTime(instDispatchingDetail.getInstallEndTime());
        instDispatchingDetail1.setInstallName(ShiroUtils.getUser().getName());
        instDispatchingDetail1.setInstallTime(new Date());
        instDispatchingDetail1.setInstallDuringRemark(instDispatchingDetail.getInstallDuringRemark());
        instDispatchingDetail1.setInstallStartTime(instDispatchingDetail.getInstallStartTime());
        instDispatchingDetail1.setInstallStatus(instDispatchingDetail.getInstallStatus());
        instDispatchingDetailRepository.save(instDispatchingDetail1);
        logService.saveLog("安装调试进度", "id：" + instDispatchingDetail1.getId() + "<br>专业：" + instDispatchingDetail1.getSpecial());

        //更新主表状态
        InstDispatchingList instDispatchingList = instDispatchingRepository.getOne(instDispatchingDetail1.getSheetId());
        List<InstDispatchingDetail> instDispatchingDetails = instDispatchingCreateMapper.findinstDispatchingDetailQuery(instDispatchingDetail1);
        int status = 0;
        int statusEnd = 0;
        for (int i = 0; i < instDispatchingDetails.size(); i++) {
            if (instDispatchingDetails.get(i).getSpecial().equals(instDispatchingDetail.getSpecial())) {
                if (instDispatchingDetail.getInstallStatus().equals("1")) {
                    status++;
                }
                if (instDispatchingDetail.getInstallStatus().equals("2")) {
                    status += 10;
                }
                if (instDispatchingDetail.getInstallStatus().equals("3")) {
                    statusEnd++;
                }
            } else {

                if (instDispatchingDetails.get(i).getInstallStatus().equals("1")) {
                    status++;
                }
                if (instDispatchingDetails.get(i).getInstallStatus().equals("2")) {
                    status += 10;
                }
                if (instDispatchingDetails.get(i).getInstallStatus().equals("3")) {
                    statusEnd++;
                }
            }
        }
        if (status > 9) {
            instDispatchingList.setInstallStatu("2");
        } else if (status <= 3 && status > 0) {
            if (statusEnd > 0) {
                instDispatchingList.setInstallStatu("2");
            } else {

                instDispatchingList.setInstallStatu("1");
            }
        } else if (status == 0) {
            instDispatchingList.setInstallStatu("3");
        } else {
            instDispatchingList.setInstallStatu("2");
        }
        instDispatchingRepository.save(instDispatchingList);
        //更新 prod_tas 表  完成状态与时间
        ProdTas prodTas = new ProdTas();
        prodTas.setProtSta(Integer.valueOf(instDispatchingList.getInstallStatu()));
        prodTas.setProtStaDat(new Date());
        prodTas.setProtCod("t26");
        prodTas.setProtNam(instDispatchingList.getProCode());
        int n = instDeliveryMapper.updateProdTas(prodTas);
        //更新销售表完成状态
        if (instDispatchingList.getInstallStatu().equals("3")){
            int  a = instDeliveryMapper.updateProStatus(instDispatchingList.getProCode().substring(0,8));
        }
//        //调取刚子的方法 验证完成  注：领导定的安装不反馈生产完成
//        String mm = instDispatchingList.getInstallStatu();
//        if (instDispatchingList.getInstallStatu().equals("3")) {
//            prodOrdService.udpCodStaAndDate(instDispatchingList.getProCode(), 3);
//        }
        //更新 prod_pla_ret 表 完成时间
        InstDelivery instDelivery = new InstDelivery();
        instDelivery.setCreateTime(new Date());
        instDelivery.setProdNo(instDispatchingList.getProCode());
        switch (instDispatchingDetail1.getSpecial()) {
            case "机械":
                instDelivery.setDept("r25");
                int a = instDeliveryMapper.updateProdPlaRet(instDelivery);
                break;
            case "流体":
                instDelivery.setDept("r26");
                int b = instDeliveryMapper.updateProdPlaRet(instDelivery);
                break;
            case "自动化":
                instDelivery.setDept("r27");
                int c = instDeliveryMapper.updateProdPlaRet(instDelivery);
                break;
        }

        return 1;
    }

    /**
     * 调试反馈明细集合
     *
     * @param debuggerAll
     * @return
     */
    public List<InstDebuggingDetail> findinstDispatchQuery(InstDebuggingDetail instDebuggingDetail) {
        return instDispatchingCreateMapper.findinstDispatchQuery(instDebuggingDetail);
    }

    /**
     * 调试附件查询
     * @param instDebuggingFile
     * @return
     */
    public List<InstDebuggingFile> findinstDebuggingFileQuery(InstDebuggingFile instDebuggingFile) {
        return instDispatchingCreateMapper.findinstDebuggingFileQuery(instDebuggingFile);
    }

    public int selectDispatchingCount() {
        return  instDispatchingCreateMapper.selectDispatchingCount();
    }

    public int selectDispatchingExamineCount() {
        return  instDispatchingCreateMapper.selectDispatchingExamineCount();
    }
}
